<template>
  <div class="yy-goods-cateogory">
    <!--列表-->
    <div class="yy-goods-cateogory-list" v-show="type=='list'">
      <Card>
        <p slot="title">
          <Icon type="md-list" />
          物品类别列表
        </p>
        <Form ref="formInline" :model="formSearch"  inline>
            <FormItem prop="user">
              <Input type="text" v-model="formSearch.cateNum" placeholder="类别编号"></Input>
            </FormItem>
            <FormItem prop="user">
              <Input type="text" v-model="formSearch.cateName" placeholder="类别名称"></Input>
            </FormItem>
            <FormItem>
              <div style="width: 56px;">
                <Button type="primary" :loading="loading"  @click="handleSearch()" style="width: 100%">
                  <span v-if="!loading">查询</span>
                  <span v-else></span>
                </Button>
              </div>
            </FormItem>
            <FormItem>
              <Button type="primary" @click="handleAdd()">新增</Button>
            </FormItem>
        </Form>
        <Table highlight-row stripe :columns="columns" :data="data" ></Table>
        <div style="margin: 10px;overflow: hidden">
          <div style="float: right;">
              <Page :total="page.total" :page-size="page.pageSize" :current="formSearch.pageNum" @on-change="changePage" show-total></Page>
          </div>
        </div>
      </Card>
    </div>
    <!--详情-->
    <div class="yy-goods-cateogory-details" v-show="type=='details'">
       <Card>
        <p slot="title">
          <Icon type="md-paper"/>
          查看详情
        </p>
        <p slot="extra">
          <Button type="primary" @click="goBack()">返回</Button>
        </p>
        <div class="details">
          <p class="details-title"><span>类别编号:</span>{{currentData.cateNum}}</p>
          <p class="details-title"><span>类别名称:</span>{{currentData.cateName}}</p>
          <p class="details-title"><span>创建人:</span>{{currentData.createUser}}</p>
          <p class="details-title"><span>创建时间:</span>{{currentData.createTime}}</p>
          <p class="details-title"><span>备注:</span>{{currentData.cateRemark}}</p>
        </div>
      </Card>
    </div>
    <!--添加/编辑-->
    <div class="yy-goods-cateogory-add-edit"  v-show="(type=='add' || type=='edit')">
      <Card>
        <p slot="title">
          <template v-if="type=='add'"> 
            <Icon type="md-create"/> 新增
          </template>
          <template v-if="type=='edit'"> 
            <Icon type="md-document"/>编辑
          </template>
        </p>
        <p slot="extra" >
          <Button type="primary" @click="goBack()">返回</Button>
        </p>
        <div class="editForm">
          <Form ref="editForm" :model="editFormInLine" :rules="editFormRuleInline" :label-width="100">
            <FormItem label="类别编号" prop="cateNum">
              <Input v-model="editFormInLine.cateNum" placeholder="如果不输入编号，后台将会自动生成" :disabled="type=='edit'? true:false"></Input>
            </FormItem> 
            <FormItem label="类别名称" prop="cateName">
              <Input v-model="editFormInLine.cateName" placeholder="请输入类别名称" :disabled="type=='edit'? true:false"></Input>
            </FormItem>
<!--             <FormItem label="创建人" prop="createUser">
              <Input v-model="editFormInLine.createUser" placeholder="请输入创建人"></Input>
            </FormItem> -->  
						<FormItem label="备注" prop="cateRemark">
							<Input v-model="editFormInLine.cateRemark" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="备注" maxlength="50"></Input>
						</FormItem>
            <FormItem>
              <Button @click="handleSubmit" type="primary" class="button">提交</Button>
              <Button @click="handleReset" type="primary" class="button">重置</Button>
            </FormItem>
          </Form>
        </div>
      </Card>
    </div>
  </div>
</template>

<script>
import API from "./api";
import ValidatorRule from "@/filters/validator-rule";
import { formatNetTime } from "@/libs/tools";
import i18n from "./locale";
import mixinTag from "@/mixin/tag-mixin";

export default {
  name: "yy-goods-cateogory",
  mixins: [mixinTag],
  data() {
    return {
      i18n: i18n,
      loading: false,
      currentData: "",
      detailsModal: false,
      type: "list",
      page: {
        total: 0,
        pageSize: 20
      },
      formSearch: {
        cateNum: "",
        cateName: "",
        userID: "",
        userName: "",
        b_UserRole: "",
        pageNum: ""
      },
      editFormInLine: {
        cateNum: "",
        cateName: "",
        cateRemark: "",
        createUser: "",
        userID: "",
        userName: "",
        b_UserRole: ""
      },
      editFormRuleInline: {
        cateName: ValidatorRule.require
      },
      columns: [
        {
          title: "类别编号",
          key: "cateNum"
        },
        {
          title: "类别名称",
          key: "cateName"
        },
        {
          title: "创建人 ",
          key: "createUser"
        },
        {
          title: "创建时间 ",
          key: "createTime"
        },
        {
          title: "备注 ",
          key: "cateRemark"
        },
        {
          title: "操作",
          key: "action",
          width: 180,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.details(params.index);
                    }
                  }
                },
                "查看"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.edit(params.index);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.delete(params.index, params.row.id);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      data: []
    };
  },

  mounted() {
    this.userInfo = this.$store.state.user.userInfo;
    this.handleSearch();
  },

  activated() {},

  computed: {},

  methods: {
    resetInit() {
      this.handleSearch();
      this.type = "list";
    },

    handleSearch() {
      let obj = this.formSearch;
      obj.pageNum = 1;
      obj.pageSize = this.page.pageSize;
      this.formSearch = obj;
      this.getList(obj);
    },

    getList(obj) {
      this.loading = true;
      API.getList(obj)
        .then(res => {
          if (res.code == 200) {
            this.loading = false;
            let data = res.data;
            if (data != null) {
              this.page.total = data.total;
              this.page.pageSize = data.pageSize;
              this.data = data.list;
            } else {
              this.$Message.success({ content: "暂无数据！" });
              this.data = [];
              this.page.total = 0;
            }
          }
        })
        .catch(err => {
          this.$Message.warning("请求异常");
          console.log("getList", err);
        });
    },

    changePage(pageNum) {
      let obj = this.formSearch,
        maxPageNum = Math.ceil(this.page.total / this.page.pageSize);
      if (obj.pageNum > maxPageNum) {
        obj.pageNum = maxPageNum;
      } else {
        obj.pageNum = pageNum;
      }
      this.formSearch = obj;
      this.getList(obj);
    },

    goBack() {
      if (this.type == "add") {
        this.$Modal.confirm({
          title: "提示：",
          content: "你确定离开吗？",
          onOk: () => {
            this.type = "list";
          }
        });
      } else {
        this.type = "list";
      }
    },

    handleAdd() {
      this.type = "add";
      this.handleReset();
    },

    details(index) {
      this.type = "details";
      this.currentData = this.data[index];
    },

    edit(index) {
      this.handleReset();
      this.type = "edit";
      this.currentData = this.data[index];
      this.editFormInLine = _.clone(this.currentData);
    },

    delete(index, id) {
      let tthis = this;
      this.$Modal.confirm({
        title: "提示：",
        content: "你确定删除这条记录",
        onOk: function() {
          let obj = {
            cateNum: tthis.data[index].cateNum,
            userID: tthis.userInfo.userId,
            userName: tthis.userInfo.userName,
            b_UserRole: ""
          };
          API.delete(obj)
            .then(res => {
              if (res.code == 200) {
                this.$Message.success({ content: "该记录已经删除成功！" });
                tthis.data.splice(index, 1);
                tthis.resetList();
              }
            })
            .catch(err => {
              this.$Message.error("请求异常！");
              console.log("delete", err);
            });
        }
      });
    },

    resetList() {
      //求余为1，页码为最大页码，请求页需减1
      let maxPageNum = Math.ceil(this.page.total / this.page.pageSize);
      let remainderNum = this.page.total % this.page.pageSize;
      if (
        this.formSearch.pageNum == maxPageNum &&
        remainderNum == 1 &&
        this.formSearch.pageNum !== 1
      ) {
        this.formSearch.pageNum = this.formSearch.pageNum - 1;
      }
      let obj = this.formSearch;
      this.getList(obj);
    },

    handleSubmit(obj) {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          if (this.type == "edit") {
            this.editSubmit(this.editFormInLine);
          } else {
            this.addSubmit(this.editFormInLine);
          }
        }
      });
    },

    handleReset() {
      this.$refs.editForm.resetFields();
      if (this.type == "edit") {
        this.editFormInLine.cateNum = this.currentData.cateNum;
        this.editFormInLine.cateName = this.currentData.cateName;
      }
    },

    editSubmit(obj) {
      (obj.b_UserRole = ""),
        API.editSubmit(obj)
          .then(res => {
            if (res.code == 200) {
              this.resetList();
              this.$Message.success("修改成功！");
              this.type = "list";
            }
          })
          .catch(err => {
            this.$Message.error("修改异常！");
            console.log("editSubmit", err);
          });
    },

    addSubmit(obj) {
      obj.userID = this.userInfo.userId;
      API.addSubmit(obj)
        .then(res => {
          if (res.code == 200) {
            this.handleSearch();
            this.$Message.success("添加成功！");
            this.type = "list";
          }
        })
        .catch(err => {
          if (err.msg) {
            this.$Message.warning(err.msg);
          } else {
            this.$Message.warning("请求异常");
          }
          console.log("addSubmit", err);
        });
    }
  }
};
</script>
<style lang="less" >
@import "./yy-goods-cateogory.less";
</style>
